import { get, post, del } from '../utils/api';
import { Comment, CommentFormData } from '../types/comment';

// 获取文章评论列表（公共接口）
export interface PaginatedResponse<T> {
  items: T[];
  total: number;
  page: number;
  pageSize: number;
  hasMore: boolean;
}

export const getArticleComments = async (articleId: string, page: number = 1, pageSize: number = 10): Promise<PaginatedResponse<Comment>> => {
  try {
    const params = { page, pageSize,articleId:parseInt(articleId) };
    const data = await get<PaginatedResponse<Comment>>(`/comments/article/${articleId}`, params);
    return data;
  } catch (error) {
    console.error('获取评论列表失败:', error);
    // 返回模拟数据
    return {
      items: [
        {
          id: '1',
          content: '这篇文章写得真好，学到了很多东西！',
          author: {
            id: 1,
            username: '张三',
            email: 'zhangsan@example.com',
            avatar: 'https://example.com/avatar.jpg',
            bio: '这是张三的个人简介'
          },
          createdAt: '2024-01-15T10:30:00Z',
          likes: 5,
          isLiked: false
        } as Comment
      ],
      total: 1,
      page: 1,
      pageSize: 10,
      hasMore: false
    }
  }
};

// 创建评论（用户接口）
export const createComment = async (articleId: string, commentData: CommentFormData): Promise<Comment> => {
  try {
    // 添加articleId到评论数据中
    const data = await post<Comment>(`/comments`, { ...commentData, articleId: parseInt(articleId) });
    return data;
  } catch (error) {
    console.error('创建评论失败:', error);
    // 模拟创建成功的评论
    return {
      id: Date.now().toString(),
      content: commentData.content,
      author: {
        id: parseInt(articleId),
        username: '当前用户',
        email: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user') || '{}').email : 'user@example.com',
        avatar: '',
        bio: '',
        createdAt: undefined as any,
        updatedAt: undefined as any
      },
      createdAt: new Date().toISOString(),
      likes: 0,
      isLiked: false
    };
  }
};

